package com.xinpu.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinpu.dto.FollowDto;
import com.xinpu.dto.UserDto;
import com.xinpu.entity.*;
import com.xinpu.enums.PublicEnum;
import com.xinpu.enums.UserEnum;
import com.xinpu.form.UserForm;
import com.xinpu.mapper.DeptMapper;
import com.xinpu.mapper.TagAdminMapper;
import com.xinpu.service.*;
import com.xinpu.util.PasswordUtils;
import com.xinpu.vo.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * UserController
 *
 * @author ayuan
 * @date 2020/12/14
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户有关接口")
public class UserController {
    @Resource
    private ITUserService itUserService;
    @Resource
    private ITFollowService itFollowService;
    @Resource
    private ITUserSourceService itUserSourceService;
    @Resource
    private ITUserTagMapService itUserTagMapService;
    @Resource
    private ITSalesService itSalesService;
    @Resource
    private ITStatusService itStatusService;
    @Resource
    private UserService userService;
    @Resource
    private ITSalesThingService itSalesThingService;
    @Resource
    private FollowService followService;
    @Resource
    private DeptService deptService;
    @Resource
    private SalesService salesService;
    @Resource
    private PhotoService photoService;
    @Resource
    private TaskService taskService;
    @Resource
    private TagAdminService tagAdminService;


    @GetMapping("/getUserInfo")
    public ResponseMessage getUserInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("introduction", "I am a super administrator");
        map.put("name", "admin");
        List<String> list = new ArrayList<>();
        list.add("admin");
        map.put("roles", list);
        return ResponseMessage.ok(map);
    }

    /**
     * 用户列表
     *
     * @param page
     * @param size
     * @param name
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/list")
    public ResponseMessage list(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestParam("type") Integer type,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "fid", required = false) Integer fid,
            @RequestParam(value = "followStatus", required = false) Integer followStatus,
            @RequestParam(value = "sex", required = false) Integer sex
    ) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(startTime)) {
            queryWrapper.between("create_time", startTime, endTime);
        }
        if (fid != null && fid > 0) {
            queryWrapper.eq("fid", fid);
        }
        if (followStatus != null) {
            queryWrapper.eq("follow_status", followStatus);
        }
        if (sex != null && !sex.toString().equals("")) {
            queryWrapper.eq("sex", sex);
        }
//        queryWrapper.gt("pid", 0);
        queryWrapper.eq("type", type);
        queryWrapper.orderByDesc("id");
        Page<TUser> tUserPage = itUserService.page(new Page<>(page, size), queryWrapper);
        ArrayList<TUserVo> tUserVos = new ArrayList<>();
        for (TUser tUser : tUserPage.getRecords()) {
            TUserVo tUserVo = new TUserVo();
            if (tUser.getAddId() == 0) {
                tUserVo.setAddId("后台添加");
            }
            tUserVo.setAddress(tUser.getAddress());
            tUserVo.setAge(tUser.getAge());
            tUserVo.setCreateTime(tUser.getCreateTime());
            tUserVo.setDemand(tUser.getDemand());
            tUserVo.setEducation(tUser.getEducation());
            QueryWrapper<TFollow> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("uid", tUser.getId());
            int count = itFollowService.count(queryWrapper1);
            tUserVo.setFollowNum(count);
            if (count != 0) {
                queryWrapper1.last("limit 1");
                tUserVo.setFollowTime(itFollowService.getOne(queryWrapper1).getCreateTime());
            }
            tUserVo.setJob(tUser.getJob());
            tUserVo.setName(tUser.getName());
            tUserVo.setOpenid(tUser.getOpenid());
            tUserVo.setPhone(tUser.getPhone());
            tUserVo.setPortrait(tUser.getPortrait());
            tUserVo.setQr(tUser.getQr());
            tUserVo.setSex(tUser.getSex());
            TSales sales = itSalesService.getById(tUser.getPid());
            if (sales != null) {
                tUserVo.setPid(sales.getName());
            }
            TStatus tStatus = itStatusService.getById(tUser.getSid());
            if (tStatus != null) {
                tUserVo.setSid(tStatus.getName());
            }
            TUserSource byId = itUserSourceService.getById(tUser.getFid());
            if (byId != null) {
                tUserVo.setSource(byId.getName());
            }
            tUserVo.setUpdateTime(tUser.getUpdateTime());
            tUserVo.setWxAccount(tUser.getWxAccount());
            tUserVo.setFollowStatus(UserEnum.toType(tUser.getFollowStatus()).getDesc());
            tUserVo.setId(tUser.getId());
            tUserVos.add(tUserVo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", tUserVos);
        map.put("total", tUserPage.getTotal());
        return ResponseMessage.ok(map);
    }

    /**
     * 创建用户
     *
     * @param userForm
     * @return
     */
    @PostMapping("/create")
    public ResponseMessage create(@RequestBody UserForm userForm) {
        if (StringUtils.isNotBlank(userForm.getPhone())) {
            TUser user = itUserService.getOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone, userForm.getPhone()));
            if (user != null) {
                return ResponseMessage.error("该手机号已存在");
            }
        }
        TUser tUser = new TUser();
        tUser.setPid(0);
        tUser.setSid(userForm.getStatus());
        tUser.setName(userForm.getName());
        tUser.setSex(userForm.getSex());
        tUser.setPhone(userForm.getPhone());
        tUser.setAddress(userForm.getAddress());
        tUser.setDemand(userForm.getDemand());
        tUser.setAddressInfo(userForm.getAddressInfo());
        tUser.setFid(userForm.getFid());
        tUser.setCompany(userForm.getCompany());
        tUser.setJob(userForm.getJob());
        tUser.setEmail(userForm.getEmail());
        tUser.setWxAccount(userForm.getWxAccount());
        tUser.setType(userForm.getType());
        if (StringUtils.isNotBlank(userForm.getBirthday())) {
            tUser.setBirthday(LocalDateTimeUtil.parse(userForm.getBirthday(), DatePattern.NORM_DATE_PATTERN));
        }
        tUser.setRemark(userForm.getRemark());
        itUserService.save(tUser);
        TUserTagMap tUserTagMap = new TUserTagMap();
        if (userForm.getTags() != null) {
            String[] split = userForm.getTags();
            for (String s : split) {
                tUserTagMap.setTid(new Integer(s));
                tUserTagMap.setUid(tUser.getId());
                itUserTagMapService.save(tUserTagMap);
            }
        }
        return ResponseMessage.ok();
    }

    /**
     * 删除用户
     *
     * @param map
     * @return
     */
    @PostMapping("/remove")
    public ResponseMessage remove(@RequestBody Map<String, Integer> map) {
        return ResponseMessage.ok(itUserService.removeById(map.get("id")));
    }

    /**
     * 编辑
     *
     * @param userForm
     * @return
     */
    @PostMapping("/update")
    public ResponseMessage update(@RequestBody UserForm userForm) {
        TUser tUser = itUserService.getById(userForm.getId());
        if (StringUtils.isNotBlank(userForm.getPhone())) {
            TUser user = itUserService.getOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone, userForm.getPhone()));
            if (user != null) {
                if (!tUser.getId().equals(user.getId())) {
                    return ResponseMessage.error("该手机号已存在");
                }
            }
        }
        tUser.setDemand(userForm.getDemand());
        tUser.setPhone(userForm.getPhone());
        tUser.setName(userForm.getName());
        if (StringUtils.isNotBlank(userForm.getBirthday())) {
            tUser.setBirthday(LocalDateTimeUtil.parse(userForm.getBirthday(), DatePattern.NORM_DATE_PATTERN));
        }
        tUser.setCompany(userForm.getCompany());
        tUser.setEmail(userForm.getEmail());
        tUser.setJob(userForm.getJob());
        tUser.setRemark(userForm.getRemark());
        tUser.setFid(userForm.getFid());
        tUser.setSex(userForm.getSex());
        if (userForm.getStatus() != null && !userForm.getStatus().toString().equals("")) {
            tUser.setSid(userForm.getStatus());
        }
        tUser.setWxAccount(userForm.getWxAccount());
        itUserService.updateById(tUser);
        if (userForm.getTags() != null) {
            itUserTagMapService.remove(Wrappers.<TUserTagMap>lambdaQuery().eq(TUserTagMap::getUid, userForm.getId()));
            //添加标签
            String[] tags = userForm.getTags();
            if (StringUtils.isNotBlank(tags[0])) {
                for (String tag : tags) {
                    TUserTagMap tUserTagMap = new TUserTagMap();
                    tUserTagMap.setTid(Integer.parseInt(tag));
                    tUserTagMap.setUid(tUser.getId());
                    itUserTagMapService.save(tUserTagMap);
                }
            }
        }
        return ResponseMessage.ok();
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public ResponseMessage findById(@RequestParam("id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("userTagList", new ArrayList<>());
        UserDto user = userService.findById(id);
        String format = "";
        if (user.getBirthday() != null) {
            format = LocalDateTimeUtil.format(user.getBirthday(), DatePattern.NORM_DATE_PATTERN);
        }
        user.setFormatBirthday(format);
        //客户标签
        List<TUserTagMap> list = itUserTagMapService.list(Wrappers.<TUserTagMap>lambdaQuery()
                .eq(TUserTagMap::getUid, id)
        );
        List<Integer> tagList = list.stream().map(TUserTagMap::getTid).collect(Collectors.toList());
        if (tagList.size() != 0) {
            List<TUserTag> userTagList = tagAdminService.userTagList(OwnService.getLoginer().getTenantId(), tagList);
            map.put("userTagList", userTagList);
        }
        map.put("user", user);
        //代办
        List<TSalesThing> thingList = itSalesThingService.list(Wrappers.<TSalesThing>lambdaQuery()
                .eq(TSalesThing::getSid, OwnService.getCurrentUserID())
                .eq(TSalesThing::getUid, id)
                .eq(TSalesThing::getSend, PublicEnum.NO.getValue())
        );
        map.put("thing", thingList);
        //协作人
        map.put("cUser", null);
        if (StringUtils.isNotBlank(user.getCid())) {
            CUserVo cUserVo = new CUserVo();
            cUserVo.setId(Integer.parseInt(user.getCid()));
            cUserVo.setName(itSalesService.getById(user.getCid()).getName());
            map.put("cUser", cUserVo);
        }
        return ResponseMessage.ok(map);
    }

    /**
     * 跟进记录
     *
     * @return
     */
    @GetMapping("/follow")
    public ResponseMessage follow(@RequestParam("id") Integer id) {
        List<FollowDto> list = followService.getList(id);
        List<FollowVo> resList = list.stream().map(x -> {
            FollowVo followVo = new FollowVo();
            followVo.setId(x.getId());
            followVo.setName(x.getName());
            followVo.setContent(x.getContent());
            if (StringUtils.isNotBlank(x.getImg())) {
                followVo.setImg(Arrays.asList(x.getImg().split(",")));
            }
            if (StringUtils.isNotBlank(x.getIvr())) {
                followVo.setIvr(Arrays.asList(x.getIvr().split(",")));
            }
            followVo.setAddress(x.getAddress());
            followVo.setType(x.getType());
            followVo.setCreateTime(x.getCreateTime());
            return followVo;
        }).collect(Collectors.toList());
        return ResponseMessage.ok(resList);
    }


    @GetMapping("/publicList")
    public ResponseMessage publicList(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestParam("type") Integer type,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "fid", required = false) Integer fid,
            @RequestParam(value = "followStatus", required = false) Integer followStatus,
            @RequestParam(value = "sex", required = false) Integer sex
    ) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(startTime)) {
            queryWrapper.between("create_time", startTime, endTime);
        }
        if (fid != null && fid > 0) {
            queryWrapper.eq("fid", fid);
        }
        if (followStatus != null) {
            queryWrapper.eq("follow_status", followStatus);
        }
        queryWrapper.eq("pid", 0);
        queryWrapper.eq("type", type);
        queryWrapper.orderByDesc("id");
        Page<TUser> tUserPage = itUserService.page(new Page<>(page, size), queryWrapper);
        ArrayList<TUserVo> tUserVos = new ArrayList<>();
        for (TUser tUser : tUserPage.getRecords()) {
            TUserVo tUserVo = new TUserVo();
            if (tUser.getAddId() == 0) {
                tUserVo.setAddId("后台添加");
            }
            tUserVo.setAddress(tUser.getAddress());
            tUserVo.setAge(tUser.getAge());
            tUserVo.setCreateTime(tUser.getCreateTime());
            tUserVo.setDemand(tUser.getDemand());
            tUserVo.setEducation(tUser.getEducation());
            QueryWrapper<TFollow> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("uid", tUser.getId());
            int count = itFollowService.count(queryWrapper1);
            tUserVo.setFollowNum(count);
            if (count != 0) {
                queryWrapper1.last("limit 1");
                tUserVo.setFollowTime(itFollowService.getOne(queryWrapper1).getCreateTime());
            }
            tUserVo.setJob(tUser.getJob());
            tUserVo.setName(tUser.getName());
            tUserVo.setOpenid(tUser.getOpenid());
            tUserVo.setPhone(tUser.getPhone());
            tUserVo.setPortrait(tUser.getPortrait());
            tUserVo.setQr(tUser.getQr());
            tUserVo.setSex(tUser.getSex());
            TSales sales = itSalesService.getById(tUser.getPid());
            if (sales != null) {
                tUserVo.setPid(sales.getName());
            }
            TStatus tStatus = itStatusService.getById(tUser.getSid());
            if (tStatus != null) {
                tUserVo.setSid(tStatus.getName());
            }
            TUserSource byId = itUserSourceService.getById(tUser.getFid());
            if (byId != null) {
                tUserVo.setSource(byId.getName());
            }
            if (sex != null && !sex.toString().equals("")) {
                queryWrapper.eq("sex", sex);
            }
            tUserVo.setUpdateTime(tUser.getUpdateTime());
            tUserVo.setWxAccount(tUser.getWxAccount());
            tUserVo.setFollowStatus(UserEnum.toType(tUser.getFollowStatus()).getDesc());
            tUserVos.add(tUserVo);
            tUserVo.setId(tUser.getId());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", tUserVos);
        map.put("total", tUserPage.getTotal());
        return ResponseMessage.ok(map);
    }

    /**
     * 数量统计
     *
     * @return
     */
    @GetMapping("/count")
    public ResponseMessage count() {
        //用户列总数
        Integer userCount = userService.userCount();
        //线索列表总数
        Integer clueCount = userService.clueCount();
        //用户公海总数
        Integer publicUserCount = userService.publicUserCount();
        //线索公海总数
        Integer publicClueCount = userService.publicClueCount();
        //部门总数
        Integer count = deptService.count();
        //销售用总数
        Integer sales = salesService.count();
        //所有用户总数
        Integer userNum = userService.userNum();
        //男性总数
        Integer manNum = userService.manNum();
        //女性总数
        Integer womanNum = userService.womanNum();
        //任务统计
        List<TaskNumVo> taskNumVos = taskService.taskNum(OwnService.getLoginer().getTenantId());
        //近七天的图文转发量
        ArrayList<PhotoNumVo> photoNumVos = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            PhotoNumVo photoNumVo = new PhotoNumVo();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(calendar.DATE, -i);
            String date = sdf.format(calendar.getTime());
            Integer num = photoService.num(OwnService.getLoginer().getTenantId(), date);
            photoNumVo.setCtreateTime(date);
            photoNumVo.setNum(num);
            photoNumVos.add(photoNumVo);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("userCount", userCount);
        map.put("clueCount", clueCount);
        map.put("publicUserCount", publicUserCount);
        map.put("publicClueCount", publicClueCount);
        map.put("count", count);
        map.put("sales", sales);
        map.put("userNum", userNum);
        map.put("manNum", manNum);
        map.put("womanNum", womanNum);
        map.put("taskNum", taskNumVos);
        map.put("photoNum", photoNumVos);
        return ResponseMessage.ok(map);
    }

}

